import java.io.*;
import java.net.*;

public class MySAXParser
{
	InputStream inStream;
	Socket inSocket;
	EventParser parser;
	int cnt;

	public MySAXParser(EventParser parser, Socket socket) throws Exception
	{
		inSocket = socket;
		this.parser = parser;
		inStream = socket.getInputStream();
		cnt = 0;
	}

	public void parse() throws Exception
	{
		parser.Reset();
		
		do {
			if(inSocket.isConnected() == false) {
				break;
			}//if
//			System.out.println("read1");
			
			char inC;
			inC = (char)inStream.read();
	
			if(inC == '\n') {
				continue;
			}//if
			
			if(inC == '<') {
				ReadElement();	
			} else {
				ReadCharacters(inC);
			}//if
		}while(cnt > 0);
	}

	public void ReadElement() throws Exception
	{
		String inStr = new String();
		char inC;

		inStr = "";

		//Read in element
		boolean done = false;
		boolean first = true;
		boolean end = false;
		while(done == false) {
			if(inSocket.isConnected() == false) {
				break;
			}//if

//			System.out.println("read2");
			
			inC = (char)inStream.read();
			switch(inC) {
				case '/':
					if(first == true) {
						end = true;
					} else {
						parser.startElement(inStr);
						parser.endElement(inStr);
						done = true;
						inC = (char)inStream.read();	//consume >
					}//if
					break;						
				case '>':
					if(end == false) {
						parser.startElement(inStr);
						cnt++;
					} else {
						parser.endElement(inStr);
						cnt--;
					}//if
					done = true;
					break;
				default:
					inStr += inC;
			}//switch
			first = false;
		}//while
	}//ReadElement

	public void ReadCharacters(char c) throws Exception
	{
		String inStr = new String();
		char inC;

		inStr += c;

		boolean done = false;
		while(done == false) {
			if(inSocket.isConnected() == false) {
				break;
			}//if
			
//System.out.println("read3");
			inC = (char)inStream.read();
	
			if(inC == '<') {
				parser.characters(inStr);
				ReadElement();
				done = true;
			} else {
				inStr += inC;

				//XXX: Terrible hack
				if(inStr.length() == 100) {
					inSocket.close();
					break;
				}//if
			}//if
		}//while
	}//ReadCharacters

}//MySAXParser


